<?php

namespace app\admin\controller\classes;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class School extends Backend
{

    /**
     * School模型对象
     * @var \app\admin\model\classes\School
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\classes\School;
        $this->view->assign("SchoolTypeList", $this->model->getSchoolTypeList());
        $this->view->assign("ContactRoleList", $this->model->getContactRoleList());

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $params = $this->request->get();
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            if(empty($params['limit']))
            {
                $limit = 1000;
            }
            else
            {
                $limit = $params['limit'];
            }

            $order = $params['order'];
            $sort = $params['sort'];


            $db2 = Db::connect('db2');
            $where = [];
//            $where['a.id'] = ['neq',1];
            $where['b.group_id'] = ['=',2];
            if(!empty($params['search']))
            {
                $where['a.nickname'] = ['like','%'.$params['search'].'%'];
            }
            $list = $db2->table('fa_admin a')
                ->join('fa_auth_group_access b','b.uid=a.id')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            /*list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['province','city','district','tiku'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);*/
            $rows = $list->items();
            foreach ($rows as $k => $row)
            {
                $rows[$k]['province'] = Db::name('area')->where('id',$row['province'])->value('name');
                $rows[$k]['city'] = Db::name('area')->where('id',$row['city'])->value('name');
                $rows[$k]['district'] = Db::name('area')->where('id',$row['district'])->value('name');
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        //作为表当选择列表走判断内
        if (isset($params['is_select']) && $params['is_select'] == 1) {
            return $this->view->fetch('/exam/cate/selectschool');
        }
        return $this->view->fetch();
    }
    
    public function admin($school_id)
    {

        $admin_model = model('Admin');

        if (false === $this->request->isAjax()) {

            $row = $this->model->with(['admin'])->find($school_id);
            $row=$row->admin;
            $row->school_id=$school_id;
            //dump($row->toArray());exit();
            $this->view->assign('row', $row);

            return $this->view->fetch();
        }

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {

                $shool_id=$params['school_id'];
                unset($params['school_id']);
                Db::startTrans();
                try {
                    if (!Validate::is($params['password'], '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $is_admin= $admin_model->where('username',$params['username'])->find();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    if ( !$is_admin){
                        $result = $admin_model->validate('Admin.add')->save($params);
                        if ($result === false) {
                            exception($admin_model->getError());
                        }
                        $group = [2];
                        $dataset = [];
                        foreach ($group as $value) {
                            $dataset[] = ['uid' => $admin_model->id, 'group_id' => $value];
                        }
                        model('AuthGroupAccess')->saveAll($dataset);
                        $this->model->where('id',$shool_id)->update(['admin_id'=>$admin_model->id]);
                    }else{
                        $result = $admin_model->validate('Admin.edit')->where('id',$is_admin->id)->update($params);
                    }

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }


                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $result=[];
        return $this->success();
    }

    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            $db2 = Db::connect('db2');
            $admin = $db2->table('fa_admin')->where('username',$params['username'])->find();
            if(!empty($admin))
            {
                $this->error('账号已存在');
            }

            Db::startTrans();
            try {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png';
                $params['createtime'] = time();
                $admin_id = $db2->table('fa_admin')->insertGetId($params);
                $data = [
                    'uid' => $admin_id,
                    'group_id' => 2
                ];
                $db2->table('fa_auth_group_access')->insertGetId($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success();
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            $id = $params['id'];
            unset($params['id']);

            $db2 = Db::connect('db2');
            $admin = $db2->table('fa_admin')->find($id);
            if(empty($admin))
            {
                $this->error('账号不存在');
            }

            Db::startTrans();
            try {
                if(empty($params['password']))
                {
                    unset($params['password']);
                }
                else
                {
                    $params['password'] = md5(md5($params['password']) . $admin['salt']);
                }
                $params['updatetime'] = time();

                $db2->table('fa_admin')->where('id',$id)->update($params);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success();
        }

        $db2 = Db::connect('db2');
        $row = $db2->table('fa_admin')->find($ids);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
}
